import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:flutter/foundation.dart';

// 加解密类
class CryptoUtil {
  // 加密
  static String encrypter(String content, String secretKey) {
    // 生成一个随机的 IV (Initialization Vector)
    final iv = encrypt.IV.fromSecureRandom(16);
    // 创建加密器，使用 AES CFB 模式
    final encrypter = encrypt.Encrypter(encrypt
        .AES(encrypt.Key.fromUtf8(secretKey), mode: encrypt.AESMode.ctr));
    // 加密
    final encrypted = encrypter.encrypt(content, iv: iv);
    return encrypt.Encrypted(Uint8List.fromList([
      ...iv.bytes,
      ...encrypted.bytes,
    ])).base64;
  }

  // 解密
  static String decrypter(String encryptedBase64, String secretKey) {
    // 解码 base64
    final encryptedBytes = encrypt.Encrypted.fromBase64(encryptedBase64).bytes;

    // 提取 IV（前16字节）
    final ivBytes = encryptedBytes.sublist(0, 16);
    final iv = encrypt.IV(ivBytes);

    // 提取加密数据（从第16字节开始）
    Uint8List cipherText = encryptedBytes.sublist(16);

    // 创建解密器，使用 AES CTR 模式
    final encrypter = encrypt.Encrypter(encrypt
        .AES(encrypt.Key.fromUtf8(secretKey), mode: encrypt.AESMode.ctr));
    // 解密
    return encrypter.decrypt(encrypt.Encrypted(cipherText), iv: iv);
  }
}
